package com.coffee_shop_app.module.ws;

import android.util.Log;

import com.coffee_shop_app.module.SingleObject;
import com.coffee_shop_app.common.vo.WebsocketVo;

import org.java_websocket.WebSocket;
import org.java_websocket.handshake.ClientHandshake;
import org.java_websocket.server.WebSocketServer;

import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.HashMap;

/**
 * Created by Roc on 2018/10/9.
 */
public class ServerSocket extends WebSocketServer  {
    private static int onlineCount = 0;
    // 存储用户信
    HashMap<String, WebSocket> onlineUserMap = new HashMap<String, WebSocket>();
    private ServerManager _serverManager;
    public  String string;
    public byte flag;

    public ServerSocket(ServerManager serverManager,int port) throws UnknownHostException {
        super(new InetSocketAddress(port));
        _serverManager=serverManager;

    }

    @Override
    public void onOpen(WebSocket webSocket, ClientHandshake handshake) {
        Log.i("TAG","Some one Connected...");
        System.out.printf("A component is connected from: %s\n", webSocket.getRemoteSocketAddress());
        onlineUserMap.put( webSocket.getRemoteSocketAddress().toString(), webSocket);
        // 通知前端设备上线
        WebsocketVo websocketVo = new WebsocketVo();
        websocketVo.setDataType("deviceUP");
        websocketVo.setUserId(webSocket.getRemoteSocketAddress().toString());
        SingleObject.getInstance().sendFEMessage(websocketVo);
    }

    @Override
    public void onClose(WebSocket webSocket, int code, String reason, boolean remote) {
        _serverManager.UserLeave((WebSocket) webSocket);
        onlineUserMap.remove(webSocket.getRemoteSocketAddress().toString());
        // 通知前端设备下线
        WebsocketVo websocketVo = new WebsocketVo();
        websocketVo.setDataType("deviceDown");
        websocketVo.setUserId(webSocket.getRemoteSocketAddress().toString());
        SingleObject.getInstance().sendFEMessage(websocketVo);
    }

    @Override
    public void onMessage(WebSocket webSocket, String message) {
        // 通知设备消息
        Log.i("TAG","OnMessage:"+message.toString());
        WebsocketVo websocketVo = new WebsocketVo();
        websocketVo.setDataType("deviceData");
        websocketVo.setData(message);
        websocketVo.setUserId(webSocket.getRemoteSocketAddress().toString());
        SingleObject.getInstance().sendFEMessage(websocketVo);
        if (message.equals("1")) {
            _serverManager.SendMessageToUser((WebSocket) webSocket, "What?");
        }
        String[] result=message.split(":");
        if (result.length==2) {
            if (result[0].equals("user")) {
                _serverManager.UserLogin(result[1], (WebSocket) webSocket);
            }
        }
    }

    @Override
    public void onError(WebSocket conn, Exception ex) {
        Log.i("TAG","Socket Exception:"+ex.toString());
        string=ex.toString();flag=1;
    }

    @Override
    public void onStart() {
    }
}